package com.zmm.util.password;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;

import java.math.BigInteger;
import java.util.UUID;

/**
 * @author 900045
 * @description:
 * @name PasswordUtil
 * @date By 2021-06-22 14:08:42
 */
public final class PasswordUtil {


	private static final BigInteger PRIVATE_D = new BigInteger(
			"3206586642942415709865087389521403230384599658161226562177807849299468150139");
	private static final BigInteger N         = new BigInteger(
			"7318321375709168120463791861978437703461807315898125152257493378072925281977");

	/**
	 * 生成 加密salt
	 * @return
	 */
	public static String genSalt() {
		return genSalt(5);
	}

	/**
	 * 生成 加密salt
	 * @param length
	 * @return
	 */
	public static String genSalt(int length) {
		return UUID.randomUUID().toString().substring(0, length);
	}

	/**
	 * MD5  + salt 加密， 不可解密
	 * @param passStr
	 * @param passSalt
	 * @return
	 */
	public static String encrypt(String passStr, String passSalt) {

		return new Md5Hash(passStr, passSalt).toString();
	}

	/**
	 * 登陆验证
	 * @param passStr
	 * @param passLogin
	 * @param salt
	 * @return
	 */
	public static boolean validate(String passStr, String passLogin, String salt) {

		return StringUtils.equals(passStr, encrypt(passLogin, salt));
	}

	/**
	 * 正则表达式验证密码必须要包含数字和大小写字母的6-20位密码
	 * @param input
	 * @return
	 */
	public static boolean rexCheckPassword(String input) {
		// 6-20 位，字母、数字、字符
		//String reg = "^([A-Z]|[a-z]|[0-9]|[`-=[];,./~!@#$%^*()_+}{:?]){6,20}$"
		//String regStr = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,20}$" //2017-05-26 18:44 替换
		String regStr = "^([A-Z]|[a-z]|[0-9]|[~!@#$%^&*\\(\\)_+\\{\\}\\|:”<>?`\\[\\]\\-\\\\=;’,./]){6,16}$";
		return input.matches(regStr);
	}
	
	/**
	 * 解密登录密码
	 * @author: 900045
	 * @date: 2021-07-26 16:45:22
	 * @throws 
	 * @param password: 
	 * @return: java.lang.String
	 **/
	public static String getDecryptLoginPassword(String password){

		byte[] pText = HexUtil.toByteArray(password);
		BigInteger encryptC = new BigInteger(pText);

		BigInteger variable = encryptC.modPow(PRIVATE_D, N);
		// 计算明文对应的字符串
		byte[] mt = variable.toByteArray();
		StringBuffer buffer = new StringBuffer();
		for (int i = mt.length - 1; i > -1; i--) {
			buffer.append((char) mt[i]);
		}
		return buffer.substring(0, buffer.length() - 10);
		
	}
}
